package scoutobahn.xml.automaton;

import java.util.Collection;
import java.util.LinkedList;

import org.xml.sax.Attributes;

import scoutobahn.xml.LazyOsmItem;
import scoutobahn.xml.OsmWay;
import scoutobahn.xml.OsmXmlTypes;
/**
 * The state for a way element.
 * @author mark
 *
 */
public class WayState extends OsmElementState {
    private Long id;
    private Collection<LazyOsmItem> nodes;
    /**
     * Constructs a new WayState with the given StateManager
     * and the given OsmItemStreamManager.
     * @param stateManager The StateManager
     * @param manager The OsmItemStreamManager
     */
    public WayState(final StateManager stateManager,
            final OsmItemStreamManager manager) {
        super(stateManager, "way", manager);
        this.nodes = new LinkedList<LazyOsmItem>();
    }

    @Override
    public ParserState startElement(final String namespace,
            final String localName,
            final String qName, final Attributes attr) {
        if (localName.equals("way")) {
            this.id = Long.parseLong(attr.getValue("id"));
        }
        if (localName.equals("nd")) {
            long ref = Long.parseLong(attr.getValue("ref"));
            LazyOsmItem nd = new LazyOsmItem(ref, null, OsmXmlTypes.Node);
            this.nodes.add(nd);
        }
        super.startElement(namespace, localName, qName, attr);
        return this;
    }

    @Override
    public ParserState endElement(final String namespace,
            final String localName, final String qName) {
        if (localName.equals("way")) {
            super.getItemStreamListener().wayFound(new OsmWay(this.id,
                    super.getTags(), nodes));
        }
        return super.endElement(namespace, localName, qName);
    }

}
